package com.fanhang.samples.spring.primitive.service.impl;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionValidationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.fanhang.samples.spring.primitive.po.User;
import com.fanhang.samples.spring.primitive.service.UserBeanService;

@Service
public class UserBeanServiceImpl implements UserBeanService, ApplicationContextAware {

	private ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	@Override
	public String register(String userName, int roleId) {
		User user = new User();
		user.setUserName(userName);
		user.setRoleId(roleId);
		String beanName = user.createBeanName();
		if (applicationContext.containsBean(beanName)) {
			Object obj = applicationContext.getBean(beanName);
			if (!(obj instanceof User)) {
				throw new ClassCastException("已存在同名bean");
			}
		} else {
			BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
			builder.addPropertyValue("userName", userName);
			builder.addPropertyValue("roleId", roleId);
			builder.addPropertyValue("", "").addPropertyValue("", "");
			
			ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
			BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext.getBeanFactory();
			beanDefinitonRegistry.registerBeanDefinition(beanName, builder.getBeanDefinition());
		}
		return beanName;
	}
	
	public User get(String userName, int roleId) {
		User user = new User();
		user.setUserName(userName);
		user.setRoleId(roleId);
		String beanName = user.createBeanName();
		if (!applicationContext.containsBean(beanName)) {
			throw new BeanDefinitionValidationException("找不到Bean");
		}
		user = applicationContext.getBean(beanName, User.class);
		return user;
	}

	@Override
	public Map<String, User> getAll() {
		String[] names = applicationContext.getBeanNamesForType(User.class, true, false);
		System.out.println(JSON.toJSONString(names));
		Map<String, User> userMap = applicationContext.getBeansOfType(User.class);
		return userMap;
	}
	
}
